<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Models\Article;
use App\Models\Article_content;
use Illuminate\Support\Facades\DB;
use Validator;


class ArticleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {

//        dd( mt_rand(strtotime('2018-11-13'),'1545369765'));

        $article_cate = '';
        $logmin = '';
        $logmax = '';
        $search_name = '';
        $search_filed = [];
        if($request->action){

            $search_filed['article_cate'] = $request->article_cate;
            $search_filed['logmin'] = $request->logmin;
            $search_filed['logmax'] = $request->logmax;
            $search_filed['search_name'] = $request->search_name;

        }

        $res =  Article::select('id','table','cagetory','originate','page_views','status','created_at')

            ->when($logmin,function ($query) use($logmin){
                return $query->where('created_at','>=',$logmin);
            })
            ->when($logmax,function ($query) use($logmax){
                return $query->where('created_at','<=',$logmax);
            })
            ->take(10)->get()->toArray();

        $data  = [
            'res'=>$res,
            'search_filed'=>$search_filed,
        ];
        return view('admin.article.article-list',$data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
*/
    public function create()
    {
        //
        return view('admin.article.form-validator');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //修改状态上架或下架状态
        $action = $request->action;
        if($action){
            return $this->$action($request);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        $res  = Article_content::with('article_content_belongsTo_article')->where('id','=',$id)->first()->toArray();
//        dd($res);
        return view('admin.article.article-add',compact('res'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {

//        dd($id);
        $ids = explode(',',$id);
//        dd($ids);
        $array = array('msg' => '删除失败!', 'status' => 'success');

        DB::beginTransaction();//开启事务需要使用ninoDB 类型数据库,一定不能忘了.
        try {
            $res1 = Article::wherein('id',$ids)->delete();
            $res2 = Article_content::whereIn('article_id',$ids )->delete();
            if ($res1 && $res2) {
                DB::commit();
                $array = array('msg' => '修改成功!', 'status' => 'success');
            }
        } catch (\Exception $e) {
            DB::rollBack();
            dump('fail');
        }

        return json_encode($array);
    }


    //store方法--修改状态
    public function status_edit_store($request)
    {
        $array = array('msg'=>'修改失败!','status'=>'false');
        if($request->status == '1'){
            $data = [
                'status' =>'2',
            ];
            $res = Article::where('id','=',$request->id)->update($data);
            if($res){
                $array = array('msg'=>'修改成功!','status'=>'success');
            }
        }
        if($request->status == '2'){
            $data = [
                'status' => '1',
            ];

            $res = Article::where('id','=',$request->id)->update($data);
            if($res){
                $array = array('msg'=>'修改成功!','status'=>'success');
            }
        }
        return json_encode($array);
    }

    //store方法--保存文章
    public function article_add($request)
    {
        $array = array('msg' => '修改失败!', 'status' => 'false');

        $form = $request->form;
        $data = [];
        foreach ($form as $k0 => $v0) {
            $name = $v0['name'];
            $data[$name] = $v0['value'];
        }

        $article_content_data = [
            'articletitle2' => $data['articletitle2'],
            'articlecolumn' => $data['articlecolumn'],
            'articletype' => $data['articletype'],
            'articlesort' => $data['articlesort'],
            'keywords' => $data['keywords'],
            'abstract' => $data['abstract'],
            'author' => $data['author'],
            'sources' => $data['sources'],
            'allowcomments' => $data['allowcomments'] ? '1' : '0',
            'content' => $data['editorValue'],
        ];


        $article_data = [
            'table' => $data['articletitle'],
        ];

        DB::beginTransaction();//开启事务需要使用ninoDB 类型数据库,一定不能忘了.
        try {
            $res1 = Article_content::where('id', '=', $data['article_content_id'])->update($article_content_data);
            $res2 = Article::where('id', '=', $data['article_id'])->update($article_data);
            if ($res1 && $res2) {
                DB::commit();
                $array = array('msg' => '修改成功!', 'status' => 'success');
            }
        } catch (\Exception $e) {
            DB::rollBack();
            dump('fail');
        }

        return json_encode($array);
    }

    //store方法--验证数据
    public function form_validate($request)
    {
        $data = $request->all();
//        dd($data);
        //验证提交数据
        $check = [
            'articletitle'=>"required|unique:articles,table",
            'articletitle2'=>"required|unique:article_content,articletitle2",
        ];
        //错误提示
        $message = [
            'articletitle.required'=>'名称必填',
            'articletitle.unique'=>'名称唯一',
            'articletitle2.required'=>'名称简称必填',
            'articletitle2.unique'=>'名称简称唯一',
        ];
        //开启验证
        $validate = Validator::make($data,$check,$message);
        //验证错误
        if ($validate->fails()) {
//            return redirect('post/create')
//                ->withErrors($validate)
//                ->withInput();

//            $error_column = [];
//            foreach($validate->messages()->all() as $v){
//                $error_column = array_search($v,$message);
//            }
            return ['status'=>'Error','error'=>$validate->messages()->all()];

        }

        $article_content_data = [
            'articletitle2' => $data['articletitle2'],
            'articlecolumn' => $data['articlecolumn'],
            'articletype' => $data['articletype'],
            'articlesort' => $data['articlesort'],
            'keywords' => $data['keywords'],
            'abstract' => $data['abstract'],
            'author' => $data['author'],
            'sources' => $data['sources'],
            'allowcomments' => $data['allowcomments'] ? '1' : '0',
            'content' => $data['editorValue'],
        ];

        $article_data = [
            'table' => $data['articletitle'],
        ];

        $array = array('error' => ['修改失败!'], 'status' => 'SUCCESS');
//        DB::beginTransaction();//开启事务需要使用ninoDB 类型数据库,一定不能忘了.
//        try {
//            $res1 = Article_content::where('id', '=', '1')->update($article_content_data);
//            $res2 = Article::where('id', '=', '1')->update($article_data);
//            if ($res1 && $res2) {
//                DB::commit();
//                $array = array('msg' => '修改成功!', 'status' => 'success');
//            }
//        } catch (\Exception $e) {
//            DB::rollBack();
//            dump('fail');
//        }
        return $array;
    }

}
